package com.gitee.slowcreator.http.file.download.template;

import com.gitee.slowcreator.http.file.download.DownloadResult;
import com.gitee.slowcreator.http.file.download.IFileDownload;
import com.gitee.slowcreator.http.util.FileNameUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zxw
 * @date 2023/6/10 18:22
 */
@Slf4j
public abstract class AbstractByteFileDownload<Request, Response> implements IFileDownload<Request, Response> {

    @Override
    public DownloadResult downloadByte(Request request, Response response) {

        if (response == null) {
            return null;
        }

        byte[] bytes = getByteData(request, response);
        DownloadResult downloadResult = new DownloadResult();
        downloadResult.setData(bytes);
        if (bytes == null || bytes.length == 0) {
            downloadResult.setRequestSuccess(false);
        } else {
            downloadResult.setRequestSuccess(true);
        }

        // 获取原始文件名称
        String dispositionHeader = getContentDisposition(request, response);
        String requestUrl = getRequestUrl(request, response);
        downloadResult.setOriginFileName(FileNameUtil.getOriginFileNameFromContentDisposition(dispositionHeader, requestUrl));

        return downloadResult;
    }

    /**
     * 获取byte数据
     *
     * @param request
     * @param response
     * @return
     */
    protected abstract byte[] getByteData(Request request, Response response);

    /**
     * 获取 Content-Disposition
     *
     * @param request
     * @param response
     * @return
     */
    protected abstract String getContentDisposition(Request request, Response response);

    /**
     * 获取请求url
     *
     * @param request
     * @param response
     * @return
     */
    protected abstract String getRequestUrl(Request request, Response response);
}
